<?php
namespace App\Http\Controllers\Client\Shop\Explore;

use App\Http\Controllers\ClientController;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class ExploreTaskController extends ClientController
{
    /**
     * 接单前挂起订单(完成任务才算接单完成)
     * @return \Illuminate\Http\JsonResponse
     */

    public function index()
    {

        $all = $this->all;

        // 查询是否正在接单
        try{
            $eo_id = $all['eo_id'];
            $task = 'explore_order_task_' . $eo_id;

            $tasking = Redis::get('explore_order_task_we_id_'.$this->we_id);
            if($tasking > 0 && $tasking != $eo_id){
                return $this->setReturnJson(-1,'您正在接单其他店铺，请接单成功后再来抢单');
            }
            $uptime = Redis::ttl($task);
            if($uptime > 0 && (Redis::get($task) != $this->we_id)){
                return $this->setReturnJson(-1,'当前订单正在由他人尝试接单,如接单失败将在'.$uptime.'秒后释放',['ttl'=>$uptime]);
            }
            if(Redis::get($task) == $this->we_id){
                return $this->setReturnJson(0,'抢单成功');
            }
        }catch (\Exception $e){
            Log::error(ExploreTaskController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'抢单失败');
        }

        // 进入接单任务
        try{
            DB::beginTransaction();
            // 查询是否已经接单完成
            $order = DB::table('explore_order')->where('eo_id','=',$eo_id)->sharedLock()->first(); // 共享锁锁定当前订单
            $order = json_decode(json_encode($order), true);
            if($order['status'] !== Data::DATA_DB_EXPLORE_ORDER_STATUS_PENDING){
                DB::rollBack();
                return $this->setReturnJson(-1,'您下手慢了，订单已被其他达人抢走啦');
            }
            if($order['task_we_id'] !== $this->we_id){ // 再次核实正在接单人，防止执行过程出错
                DB::rollBack();
                $uptime = Redis::ttl($task);
                if($uptime > 0){ // 如果存在正在接单人退出，否则取代这个人
                    return $this->setReturnJson(-1,'当前订单正在由他人尝试接单,如接单失败将在'.$uptime.'秒后释放',['ttl'=>$uptime]);
                }
            }
            // 验证没有问题，添加一个正在进行任务的标识
            DB::table('explore_order')->where('eo_id','=',$eo_id)->update(['task_we_id'=>$this->we_id]);
            Redis::setex('explore_order_task_'.$eo_id, 10*60, $this->we_id);
            Redis::setex('explore_order_task_we_id_'.$this->we_id,10*60, $eo_id);
            DB::commit();
            return $this->setReturnJson(0,'抢单成功');
        }catch (\Exception $e){
            DB::rollBack();
            Log::error(ExploreTaskController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'抢单失败');
        }
    }

}
